package com.datastructure.test.deletelistnode;

public class DeleteListNode {

    public static void main(String[] args) {
        DeleteListNode deleteListNode = new DeleteListNode();
        ListNode root = new ListNode(2);
        root.next=new ListNode(5);
        root.next.next=new ListNode(1);
        root.next.next.next=new ListNode(9);
        ListNode deleteNode = deleteListNode.deleteNode(root, 5);
        System.out.println(deleteNode);
    }

    public ListNode deleteNode (ListNode head, int val) {
        // write code here
        ListNode lastListNode = null;
        ListNode cur = head;
        while (head!=null){
            if(head.val==val){
                if(lastListNode==null){
                    cur=head.next;
                    break;
                } else {
                    lastListNode.next=head.next;
                }
            }
            lastListNode=head;
            head=head.next;
        }
        return cur;
    }
}
class ListNode {
   int val;
   ListNode next = null;
   public ListNode(int val) {
     this.val = val;
   }
 }
